package com.lagou.server;

import com.lagou.container.StandardService;
import com.lagou.servlet.HttpServlet;
import com.lagou.util.RequestProcessor;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

public class Server {

    private StandardService standardService;

    public StandardService getStandardService() {
        return standardService;
    }

    public void setStandardService(StandardService standardService) {
        this.standardService = standardService;
    }

    public void start() throws IOException {
        loadServlet();

        int corePoolSize = 10;
        int maximumPoolSize =50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);

        ServerSocket serverSocket = new ServerSocket(getStandardService().getPorts());
        System.out.println("starting.....");

        /**
         * minicat3.6版本，添加线程,使用线程池
         */
        while(true){
            Socket accept = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(accept, getStandardService());
            threadPoolExecutor.execute(requestProcessor);
        }
    }

    private void loadServlet() {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("config/server.xml");

        try {

            standardService = new StandardService(resourceAsStream);
            //约定这里只有一个Service
            standardService.init();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Server starter = new Server();
        try {
            starter.start();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
